package api.util;

import com.alibaba.fastjson.JSONObject;
import m.common.model.Model;
import m.common.model.util.ModelQueryList;
import m.common.model.util.ModelUpdateUtil;
import m.common.model.util.QueryCondition;
import m.system.util.ClassUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

public class ApiMigrationSaveProgress {
    private final String tableClass;
    private final List<JSONObject> modelList;
    public ApiMigrationSaveProgress(String tableClass,List<JSONObject> modelList){
        this.tableClass=tableClass;
        this.modelList=modelList;
    }
    public void saveAll() throws Exception {
        try {
            Class<? extends Model> clazz = ClassUtil.getClass(Model.class, tableClass);
            List<Model> ls = new ArrayList<>();
            for (JSONObject json : modelList) {
                ls.add(json.toJavaObject(clazz));
            }
            List<String> hasOids = ModelQueryList.getModelList(clazz, new String[]{"oid"}, null,
                            QueryCondition.in("oid", ls.stream().map(Model::getOid).toArray()))
                    .stream().map(Model::getOid).collect(Collectors.toList());
            List<Model> insertLs = new ArrayList<>();
            List<Model> updateLs = new ArrayList<>();
            for (Model model : ls) {
                if (hasOids.contains(model.getOid())) {
                    updateLs.add(model);
                } else {
                    insertLs.add(model);
                }
            }
            if (!insertLs.isEmpty()) ModelUpdateUtil.insertModels(insertLs.toArray(new Model[0]));
            if (!updateLs.isEmpty()) ModelUpdateUtil.updateModels(updateLs.toArray(new Model[0]));
        }catch (Exception e){
            e.printStackTrace();
            throw e;
        }
    }
}
